package com.entmanage.base.memo.service.impl;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.entmanage.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.entmanage.common.utils.SecurityUtils;
import com.entmanage.base.memo.mapper.MemoReminderMapper;
import com.entmanage.base.memo.domain.MemoReminder;
import com.entmanage.base.memo.service.IMemoReminderService;
import org.springframework.web.util.HtmlUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 备忘录提醒Service业务层处理
 *
 * @author lsq
 * @date 2025-09-04
 */
@Service
public class MemoReminderServiceImpl implements IMemoReminderService
{
    private static final Logger log = LoggerFactory.getLogger(MemoReminderServiceImpl.class);

    @Autowired
    private MemoReminderMapper memoReminderMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String fromEmail;

    /**
     * 查询备忘录提醒
     *
     * @param id 备忘录提醒主键
     * @return 备忘录提醒
     */
    @Override
    public MemoReminder selectMemoReminderById(Long id)
    {
        return memoReminderMapper.selectMemoReminderById(id);
    }

    /**
     * 查询备忘录提醒列表
     *
     * @param memoReminder 备忘录提醒
     * @return 备忘录提醒
     */
    @Override
    public List<MemoReminder> selectMemoReminderList(MemoReminder memoReminder)
    {
        return memoReminderMapper.selectMemoReminderList(memoReminder);
    }

    /**
     * 新增备忘录提醒
     *
     * @param memoReminder 备忘录提醒
     * @return 结果
     */
    @Override
    public int insertMemoReminder(MemoReminder memoReminder)
    {
        // 保存用户id和部门id
        memoReminder.setUserId(SecurityUtils.getUserId());
        memoReminder.setDeptId(SecurityUtils.getDeptId());
        memoReminder.setCreateBy(SecurityUtils.getUsername());
        // 将 List<String> 拼接为逗号分隔的字符串
        if (memoReminder.getRemindEmails() != null && !memoReminder.getRemindEmails().isEmpty()) {
            String emailStr = String.join(",", memoReminder.getRemindEmails());
            // 存入数据库字段
            memoReminder.setRemindEmail(emailStr);
        } else {
            // 或 null
            memoReminder.setRemindEmail("");
        }
        return memoReminderMapper.insertMemoReminder(memoReminder);
    }

    /**
     * 修改备忘录提醒
     *
     * @param memoReminder 备忘录提醒
     * @return 结果
     */
    @Override
    public int updateMemoReminder(MemoReminder memoReminder)
    {
    memoReminder.setUpdateBy(SecurityUtils.getUsername());
        if (memoReminder.getRemindEmails() != null && !memoReminder.getRemindEmails().isEmpty()) {
            String emailStr = String.join(",", memoReminder.getRemindEmails());
            memoReminder.setRemindEmail(emailStr);
        } else {
            memoReminder.setRemindEmail("");
        }
        return memoReminderMapper.updateMemoReminder(memoReminder);
    }

    /**
     * 批量删除备忘录提醒
     *
     * @param ids 需要删除的备忘录提醒主键
     * @return 结果
     */
    @Override
    public int deleteMemoReminderByIds(Long[] ids)
    {
        return memoReminderMapper.deleteMemoReminderByIds(ids);
    }

    /**
     * 删除备忘录提醒信息
     *
     * @param id 备忘录提醒主键
     * @return 结果
     */
    @Override
    public int deleteMemoReminderById(Long id)
    {
        return memoReminderMapper.deleteMemoReminderById(id);
    }

    /**
     * 发送提醒邮件
     */
    @Override
    @Async
    public void sendReminderEmail(Long id) {
        log.info("【开始发送邮件】ID={}", id);

        // 1. 查询备忘录
        MemoReminder reminder = memoReminderMapper.selectMemoReminderById(id);
        if (reminder == null) {
            log.warn("备忘录不存在，ID={}", id);
            return;
        }

        String title = reminder.getTitle();
        String content = reminder.getContent();
        String remindEmail = reminder.getRemindEmail();

        if (StringUtils.isEmpty(remindEmail)) {
            log.warn("邮件发送失败：收件人为空，ID={}", id);
            return;
        }

        try {
            // 2. 发送邮件
            SimpleMailMessage message = new SimpleMailMessage();
            message.setTo(remindEmail);
            message.setSubject("⏰ 提醒：" + (StringUtils.isNotEmpty(title) ? title : "未命名提醒"));
            message.setText(content + "\n\n—— 来自您的备忘录系统");
            message.setFrom("1911708828@qq.com");

            javaMailSender.send(message);

            log.info("邮件发送成功，收件人：{}", remindEmail);

            // 3. 更新发送状态（需解决 SecurityContext 丢失问题）
            updateSendStatus(id, true);

        } catch (Exception e) {
            log.error("发送邮件异常，ID: {}", id, e);
            updateSendStatus(id, false);
        }
    }

    /**
     * 更新发送状态
     */
    private void updateSendStatus(Long id, boolean success) {
        MemoReminder update = new MemoReminder();
        update.setId(id);
        update.setIsSent(success ? 1 : 0);
        update.setUpdatedTime(new Date());

        try {
            // 这里不要用 SecurityUtils，除非你解决了上下文传递
            // update.setUpdateBy(SecurityUtils.getUsername()); // 可能报错
            memoReminderMapper.updateMemoReminder(update);
        } catch (Exception e) {
            log.error("更新发送状态失败 ID: {}", id, e);
        }
    }

    /**
     * 构建 HTML 邮件内容
     */
    private String buildEmailContent(MemoReminder reminder) {
        String remindTimeStr = new java.text.SimpleDateFormat("yyyy-MM-dd")
                .format(reminder.getRemindTime());
        LocalDate remindDate = LocalDate.parse(remindTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        long daysUntil = java.time.temporal.ChronoUnit.DAYS.between(java.time.LocalDate.now(), remindDate);

        String typeLabel = "其他";
        switch (reminder.getMemoType()) {
            case "todo": typeLabel = "待办事项"; break;
            case "birthday": typeLabel = "生日提醒"; break;
            case "meeting": typeLabel = "会议提醒"; break;
        }

        return "<div style='font-family:Arial,sans-serif;line-height:1.6;'>" +
                "<h2>📅 备忘提醒</h2>" +
                "<p><strong>标题：</strong>" + org.springframework.web.util.HtmlUtils.htmlEscape(reminder.getTitle()) + "</p>" +
                "<p><strong>类型：</strong>" + typeLabel + "</p>" +
                "<p><strong>提醒时间：</strong>" + remindDate + "</p>" +
                "<p><strong>提前 " + reminder.getAdvanceDays() + " 天提醒</strong></p>" +
                "<p><strong>内容：</strong><br/>" + formatContent(reminder.getContent()) + "</p>" +
                "<p><em>距离到期还有 " + daysUntil + " 天</em></p>" +
                "<hr>" +
                "<p><small>发送时间：" + java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) + "</small></p>" +
                "</div>";
    }

    private String formatContent(String content) {
        if (content == null) {
            return "";
        }
        return content.replace("\n", "<br/>").replace(" ", "&nbsp;");
    }

    // 判断某个用户今天是否有“生日提醒”
    @Override
    public boolean existsReminder(MemoReminder reminder) {
        return memoReminderMapper.selectCount(reminder) > 0;
    }

}
